package fr.sedoo.commons.client.language.ui.widget;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.place.shared.PlaceChangeEvent;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Image;

import fr.sedoo.commons.client.image.CommonBundle;
import fr.sedoo.commons.client.mvp.BasicClientFactory;
import fr.sedoo.commons.client.util.LocaleUtil;

public class LanguageSwitch extends HorizontalPanel implements ClickHandler {

	private HashMap<Image, String> languageMap = new HashMap<Image, String>();
	private BasicClientFactory clientFactory;

	public LanguageSwitch(List<String> languages, BasicClientFactory clientFactory) {
		super();
		CommonBundle.INSTANCE.commonStyle().ensureInjected();
		this.clientFactory = clientFactory;
		Iterator<String> iterator = languages.iterator();
		while (iterator.hasNext()) {
			String language = iterator.next();
			Image languageFlag = LocaleUtil.getLanguageFlag(language);
			languageFlag.setStyleName(CommonBundle.INSTANCE.commonStyle().clickable());
			if (iterator.hasNext()) {
				languageFlag.addStyleName(CommonBundle.INSTANCE.commonStyle().rightMargin3px());
			}
			languageFlag.addClickHandler(this);
			languageMap.put(languageFlag, language);
			add(languageFlag);
		}
	}

	@Override
	public void onClick(ClickEvent event) {
		Image source = (Image) event.getSource();
		String language = languageMap.get(source);
		clientFactory.getEventBus().fireEvent(new PlaceChangeEvent(clientFactory.getLanguageSwitchPlace(language)));
	}
}
